package com.sh.apibackend.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.sh.apibackend.common.ErrorCode;
import com.sh.apibackend.constant.UserConstant;
import com.sh.apibackend.exception.BusinessException;
import com.sh.apibackend.mapper.UserMapper;
import com.sh.apibackend.model.dto.user.UserRegisterRequest;
import com.sh.apibackend.model.enums.UserRoleEnum;
import com.sh.apibackend.model.vo.LoginUserVO;
import com.sh.apibackend.model.vo.QQToJMSMessage;
import com.sh.apibackend.model.vo.UserDevKeyVO;
import com.sh.apibackend.service.UserService;
import com.sh.apibackend.utils.EmailCaptchaMqUtils;
import com.sh.apibackend.utils.JwtUtils;
import com.sh.apibackend.utils.LeakyBucket;
import com.sh.apicommon.entity.User;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;


import java.util.concurrent.TimeUnit;

import static com.sh.apibackend.constant.UserConstant.ADMIN_ROLE;
import static com.sh.apibackend.constant.UserConstant.USER_LOGIN_STATE;


/**
 * 用户服务实现类
 *
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private Gson gson;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

        @Resource
    private EmailCaptchaMqUtils emailCaptchaMqUtils;

    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "shapi";

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        // String.intern()是一个用于返回字符串对象在字符串常量池中的引用的方法
        synchronized (userAccount.intern()) {
            // 账户不能重复
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userAccount", userAccount);
            long count = userMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            // 2. 加密
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

            //给用户分配调用接口的公钥和私钥ak,sk，保证复杂的同时要保证唯一
            String accessKey = DigestUtil.md5Hex(SALT + userAccount + RandomUtil.randomNumbers(5));
            String secretKey = DigestUtil.md5Hex(SALT + userAccount + RandomUtil.randomNumbers(8));

            // 3. 插入数据
            User user = new User();
            user.setUserAccount(userAccount);    // 用户账号
            user.setUserPassword(encryptPassword);    // 用户密码
            user.setAccessKey(accessKey);    // 用户公钥
            user.setSecretKey(secretKey);    // 用户私钥
            user.setUserName(userAccount);    // 用户昵称
            boolean saveResult = this.save(user);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            return user.getId();
        }
    }

    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 3. 记录用户的登录态
//        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        // 存redis
        return setLoginUser(response, user);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Long userId = JwtUtils.getUserIdByToken(request);
        if (userId == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        String userJson = stringRedisTemplate.opsForValue().get(USER_LOGIN_STATE + userId);
        User user = gson.fromJson(userJson, User.class);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return user;
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
//        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
//        User user = (User) userObj;
//        return user != null && ADMIN_ROLE.equals(user.getUserRole());
        User loginUser = getLoginUser(request);
        return isAdmin(loginUser);
    }

    @Override
    public boolean isAdmin(User user) {
        String userRole = user.getUserRole();  // 当前用户角色
        return UserRoleEnum.ADMIN.getValue().equals(userRole) && user != null;
    }

    /**
     * 用户注销
     *
     * @param request
     */
    @Override
    public boolean userLogout(HttpServletRequest request, HttpServletResponse response) {
        // 从请求中获取所有的 Cookie
        Cookie[] cookies = request.getCookies();
        // 遍历所有 Cookie，查找名为 "token" 的 Cookie
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("token")) {
                // 解析 token，获取用户 ID
                Long userId = JwtUtils.getUserIdByToken(request);
                // 删除 Redis 中该用户的登录态信息（登录状态的缓存）
                stringRedisTemplate.delete(USER_LOGIN_STATE + userId);
                // 创建一个同名的新 Cookie，并设置为立即过期（MaxAge 为 0），用以覆盖客户端 Cookie，实现登出效果
                Cookie timeOutCookie = new Cookie(cookie.getName(), cookie.getValue());
                timeOutCookie.setMaxAge(0); // 设置过期时间为 0，表示立即删除
                timeOutCookie.setPath("/"); // ⚠️必须设置 path，确保清除作用域一致的 cookie
                response.addCookie(timeOutCookie); // 添加到响应中，通知浏览器清除 Cookie
                // 返回登出成功
                return true;
            }
        }
        // 如果没有找到名为 "token" 的 Cookie，说明用户未登录，抛出异常
        throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
    }



    /**
     * 记录用户的登录态，并返回脱敏后的登录用户
     *
     * @param response
     * @param user
     * @return
     */
    private LoginUserVO setLoginUser(HttpServletResponse response, User user) {
        String token = JwtUtils.getJwtToken(user.getId(), user.getUserName());
        Cookie cookie = new Cookie("token", token);
        // setPath("/") 这意味着该 Cookie 在整个网站下的所有路径中都有效
        cookie.setPath("/");
        response.addCookie(cookie);
        String userJson = gson.toJson(user);
        // 用户状态存储到redis
        stringRedisTemplate.opsForValue().set(USER_LOGIN_STATE + user.getId(), userJson, JwtUtils.EXPIRE, TimeUnit.MILLISECONDS);
        return this.getLoginUserVO(user);
    }

    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    /**
     * 重新生成密钥
     *
     * @param request
     * @return
     */
    @Override
    public UserDevKeyVO regenerationKey(HttpServletRequest request) {
        User loginUser = getLoginUser(request);  // 获取当前登录用户
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 生成新的密钥
        UserDevKeyVO userDevKeyVO = new UserDevKeyVO();
        String userAccount = loginUser.getUserAccount();
        //给用户分配调用接口的公钥和私钥ak,sk，保证复杂的同时要保证唯一
        String accessKey = DigestUtil.md5Hex(SALT + userAccount + RandomUtil.randomNumbers(5));
        String secretKey = DigestUtil.md5Hex(SALT + userAccount + RandomUtil.randomNumbers(8));
        userDevKeyVO.setAccessKey(accessKey);
        userDevKeyVO.setSecretKey(secretKey);

        // 更新数据库
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", loginUser.getId());
        updateWrapper.eq("userAccount", loginUser.getUserAccount());
        updateWrapper.set("accessKey", accessKey);
        updateWrapper.set("secretKey", secretKey);
        this.update(updateWrapper);   // 更新数据库

        // 更新redis
        String userJson = gson.toJson(loginUser);

        // user:login:1{xxx:xxx}  500s
        stringRedisTemplate.opsForValue().set(UserConstant.USER_LOGIN_STATE
                        + loginUser.getId(),
                userJson,
                JwtUtils.EXPIRE,
                TimeUnit.MILLISECONDS);
        return userDevKeyVO;
    }


    /**
     * 邮件注册
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean userEmailRegister(UserRegisterRequest userRegisterRequest, String emailCaptcha) {
        //  1.名字是否用过
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userRegisterRequest.getUserAccount())
                .or()
                .eq("email", userRegisterRequest.getEmail());
        User one = this.getOne(queryWrapper);
        if ( one !=null){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户名或邮箱已存在");
        }
        if (!userRegisterRequest.getUserPassword().equals(userRegisterRequest.getCheckPassword())) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "两次密码不一致");
        }
        User user = new User();
        user.setUserName(userRegisterRequest.getUserAccount());
        user.setUserAccount(userRegisterRequest.getUserAccount());
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userRegisterRequest.getUserPassword()).getBytes());
        user.setUserPassword(encryptPassword);
        // 3. 密钥
        String accessKey = DigestUtil.md5Hex(SALT + userRegisterRequest.getUserAccount() + RandomUtil.randomNumbers(5));
        String secretKey = DigestUtil.md5Hex(SALT + userRegisterRequest.getUserAccount() + RandomUtil.randomNumbers(8));
        user.setAccessKey(accessKey);
        user.setSecretKey(secretKey);
        user.setEmail(userRegisterRequest.getEmail());
        boolean save = this.save(user);
        return save;
    }

    @Override
    public boolean sendToJMS(QQToJMSMessage qqToJMSMessage) {
        String email = "emailNum:";
        synchronized (qqToJMSMessage) {
            Boolean registerEmail = stringRedisTemplate.hasKey(email+ qqToJMSMessage.getQqEmail());
            if ( registerEmail!=null && registerEmail){
                // 漏桶算法
                long lastTime=0L;
                String strLastTime = stringRedisTemplate.opsForValue().get(email + qqToJMSMessage.getQqEmail());  // 获取上一次发送时间
                if (strLastTime!=null){
                    lastTime = Long.parseLong(strLastTime);  // 上一次发送时间
                }
                if (!LeakyBucket.registerEmailLeakyBucket.control(lastTime)){
                    log.info("邮箱发送太频繁了");
                    throw new BusinessException(ErrorCode.PARAMS_ERROR,"邮箱送太频繁了");
                }
            }
        }
        emailCaptchaMqUtils.sendQQEmailToJMS(qqToJMSMessage);
        //更新发送邮件的时间
        stringRedisTemplate.opsForValue().set(email + qqToJMSMessage.getQqEmail(),System.currentTimeMillis()/1000+"",1,TimeUnit.MINUTES);
        return  true;
    }
}




